var selectName='mainId,id,parentId,deviceName,mdmCode,stationNames,mdmMainFlag,isEdit,isComplete';//查找字段
//创建打开数据库
function createDb(name) {
  plus.sqlite.openDatabase({
    name: name,
    path: '_doc/' + name + '.db',
    success: function(e) {
      console.log('openDatabase success!');
    },
    fail: function(e) {
      console.log('openDatabase failed: ' + JSON.stringify(e));
    }
  });
}

//判断数据库是否打开
function validBdOpen(name) {
  return plus.sqlite.isOpenDatabase({
    name: name,
    path: '_doc/' + name + '.db'
  });
}


// 关闭数据库
function closeDB(name) {
  plus.sqlite.closeDatabase({
    name: name,
    success: function(e) {
      console.log('数据库关闭 success!');
    },
    fail: function(e) {
      console.log('数据库关闭 failed: ' + JSON.stringify(e));
    }
  });
}

// 执行事务 begin（开始事务）、commit（提交）、rollback（回滚）。
function transactionDB(name, operation) {
  plus.sqlite.transaction({
    name: name,
    operation: operation,
    success: function(e) {
      console.log('transaction success!');
    },
    fail: function(e) {
      console.log('transaction failed: ' + JSON.stringify(e));
    }
  });
}

// 执行SQL语句
function executeListSQL(name, baseSql) {
  plus.sqlite.executeSql({
    name: name,
    sql: baseSql,
    success: function(e) {
      console.log('executeSql success!');
      // plus.sqlite.executeSql({
      // 	name: name,
      // 	sql: sql,
      // 	success: function(e){
      // 		console.log('写入成功 success!');
      // 	},
      // 	fail: function(e){
      // 		console.log('写入失败 failed: '+JSON.stringify(e));
      // 	}
      // });
    },
    fail: function(e) {
      console.log('executeSql failed: ' + JSON.stringify(e));
    }
  });
}

// 查询SQL语句
function selectListSQL(name, sql, success) {
  plus.sqlite.selectSql({
    name: name,
    sql: sql,
    success: function(data) {
      console.log('selectSql success: ');
      if (data.length == 0) {
        // alert("查询为空")
      }
      success(data)
    },
    fail: function(e) {
      console.log('selectSql failed: 失败' + JSON.stringify(e));

    }
  });
}

var childDocuments = null; //子设备
var files = null; //文件
var peopleList = null; //责任人
var queue = new Queue();//文件队列
var idList = new Queue();//id队列
var databaseName = "offlineFiles"; //定义表的名字
var bdName = "files"; //数据库的名字
var PName = "offlinePeople"; //责任人的名字
var batchList=[];//当前批量离线的数据
//队列
function Queue() {
  var items = [];
  this.enqueue = function(ele) {
    items.push(ele);
  }; //入队
  this.dequeue = function() {
    return items.shift();
  }; //出队
  this.front = function() {
    return items[0];
  }; //查看队头元素
  this.isEmpty = function() {
    return items.length === 0;
  }; //判断队列是否为空
  this.size = function() {
    return items.length;
  }; //队列大小
  this.clear = function() {
    items = [];
  }; //清空队列
  this.print = function() {
    console.log(items.toString());
  }; //打印队列
}
 
function batchOffline(list,ids){
  plus.nativeUI.showWaiting('存储中...');
    // console.log(list.length);
    // console.log(ids.length);
    batchList=list;
  var baseSql = 'create table if not exists ' + databaseName +
    '("mainId" CHAR(100),"id" CHAR(100),"parentId" CHAR(100),"deviceName" CHAR(1000),"mdmCode" CHAR(100),"stationNames" CHAR(1000),"mdmMainFlag" text,"isEdit" INT(100),"isComplete" INT(100),"detail" text)';
  executeListSQL(bdName, baseSql); //创建设备表
  list.forEach(function(item,index){
    selectListSQL(bdName, "select "+ selectName +" from " + databaseName + " WHERE id ='" + item.id + "'", function(data) {
      console.log('查出数据表数据'+data.length);
      if (data.length > 0) {
        var baseSql = "UPDATE offlineFiles SET id ='" + item.id + "' WHERE id ='" + item.id + "'";
        selectListSQL(bdName, baseSql, function(data) {
          if(index===list.length-1){
             plus.nativeUI.closeWaiting();
            console.log("true");
            var page = plus.webview.getWebviewById('../ddms/home.html');
             mui.fire(page, 'homeOffline', {
              idList: ids,
              batchList:batchList
             });
          }
        });
      } else {  
        var sql = "insert into " + databaseName + "(mainId,id,parentId,deviceName,mdmCode,stationNames,mdmMainFlag,isEdit,isComplete) values('" + item.id + "','" + item.id + "','" + item.parentId + "','" + item.deviceName + "','" + item.mdmCode + "','" + item.stationNames + "','" + item.model.mdmMainFlag + "',0,0)";
        selectListSQL(bdName, sql, function(data) {
          if(index===list.length-1){
             plus.nativeUI.closeWaiting();
            console.log("true")
            var page = plus.webview.getWebviewById('../ddms/home.html');
             mui.fire(page, 'homeOffline', {
              idList: ids,
              batchList:batchList
             });
          }
        });
      }
    
    });
  })
  
}
function receive(ids,list){
  ids.forEach(function(item,index){
    idList.enqueue(item);
  });
  batchList=list;
  childIds();
}
//循环选择队列
function childIds() {
  
  console.log(idList.size())
  var eliminated;
  while (!idList.isEmpty()) {
    eliminated = idList.dequeue();
    child(eliminated)
    console.log(eliminated + '被淘汰');
  }
  if(idList.isEmpty()){
    plus.nativeUI.closeWaiting();
  }
}
//获取所有设备方法
function child(id) {
  mui.baseApp.httpRequst("/api/metadataDocument/getAllChildDocuments", {
    isTree: false,
    parentId: id
  }, function(ChildDocuments) {
    childDocuments = ChildDocuments
    ChildDocuments.forEach(function(data, index) {
      let { childDocuments, model } = data;
      let { childModels, propDatas } = model;
      if (propDatas) {
       var enumNames = [];
        propDatas.forEach(propData => {
          if (propData.mdPropType == 10 && propData.attachmentPath) {
            queue.enqueue(propData); //初始化，进入文件队列
          }
        });
      }
      
    })

    offlineData(ChildDocuments,id,function(data){
      if(data){
        var baseSql = "UPDATE " + databaseName + " SET isComplete = 1 WHERE id ='" + id + "'";
        executeListSQL(bdName, baseSql);//此主设备已下载完成 
        var filespage = plus.webview.getWebviewById("../help/files.html");
        if(filespage){
          mui.fire(filespage,'update');
        } 
        var filesDetail = plus.webview.getWebviewById("../help/filesDetail.html");
        if(filesDetail){
          mui.fire(filesDetail,'update');
        }
        
      }
    });   
    hotPotato();
    people(id);
  }, function() {
    // plus.nativeUI.closeWaiting();
    console.log("获取数据失败");
  })
}

//离线档案
function offlineData(data,id,callback){
  // console.log(length)
  var currentData = batchList.filter(
    element => element.id == id
  );
  var iscom=false;
  var list=data;
  list.forEach(function(item, index) {
    selectListSQL(bdName, "select "+ selectName +" from " + databaseName + " WHERE id ='" +item.id + "'", function(data) {
      if (data.length > 0) {
        if(currentData[0].model.mdmMainFlag){//判断当前是否是主设备
          baseSql = "UPDATE " + databaseName + " SET detail ='" + JSON.stringify(item) + "',mainId='"+ id +"' WHERE id ='" + item.id + "'";
        }
        var baseSql = "UPDATE offlineFiles SET detail ='" + JSON.stringify(item) + "' WHERE id ='" + item.id + "'";
        selectListSQL(bdName, baseSql, function(data) {
          if (list.length - 1 === index) {  
            iscom=true;
            callback(iscom);
            childIds();
          }
        });
      } else {
        var sql = "insert into " + databaseName + " values('" + id + "','" + item.id + "','" + item.parentId + "','" + item.deviceName + "','" + item.mdmCode + "','" + item.stationNames + "','" + item.model.mdmMainFlag + "',0,0,'" + JSON.stringify(item) + "')";
        selectListSQL(bdName, sql, function(data) {
          if(index===list.length-1){
            iscom=true;
            callback(iscom);
            childIds();
          }
        });
      }
     
    });
    // iscom=true;
  })
  
  
}
//离线责任人
function people(id) {
  var baseSql = 'create table if not exists ' + PName +
    '("id" CHAR(100),"type" CHAR(100),"documentId" CHAR(1000),"userId" CHAR(100),"username" CHAR(100),"phone" CHAR(100),"employeeNo" text,"realname" text,"deptName" text,"source" text)';
  executeListSQL(bdName, baseSql); //创建责任人表
  mui.baseApp.httpRequst("/api/metadataDocument/getAllDocumentsManager", {
    copyFlag: false,
    childModelFlag: true,
    id: id
  }, function(data) {
    peopleList = data;
    offlinePeople(peopleList);
  }, function() {
    plus.nativeUI.closeWaiting();
    console.log("获取数据失败");
  })
}

//离线责任人
function offlinePeople() {
  peopleList.forEach(function(item, index) {
    selectListSQL(bdName, "select * from " + PName + " WHERE employeeNo='" + item.employeeNo + "'",
      function(data) {
        // console.log('查出数据表数据' + JSON.stringify(data));
        if (data.length > 0) {
          var baseSql = "UPDATE " + PName + " SET username ='" + item.username + "',deptName ='" +
            item.deptName + "',type= '" + item.type + "',realname = '" + item.realname + "',source='" +
            item.source + "',documentId='" + item.documentId + "'  WHERE employeeNo ='" + item.employeeNo + "'";
          selectListSQL(bdName, baseSql, function(data) {});
        } else {
          var sql = "insert into " + PName + " values('" + item.id + "','" + item.type + "','" + item
            .documentId + "','" + item.userId + "','" + item.username + "','" + item.phone + "','" +
            item.employeeNo + "','" + item.realname + "','" + item.deptName + "','" + item.source +
            "')";
          executeListSQL(bdName, sql);

        }

      });
  })
}

function hotPotato() {
  console.log(queue.size())
  var eliminated;
  while (!queue.isEmpty()) {
    eliminated = queue.dequeue();
    dTask(eliminated)
    console.log(eliminated + '被淘汰');
  }
}
//下载文件
function dTask(item) {
  var isUrl = false;
  var FileSystemURL = "_downloads/" + item.id + "/" + item.attachmentName;
  plus.io.resolveLocalFileSystemURL(FileSystemURL, function() {
    console.log('一下载');
    hotPotato();
  }, function() {
    var dtask = plus.downloader.createDownload(item.attachmentPath, {
      filename: "_downloads/" + item.id + "/" + item.attachmentName
    }, function(
      d, status) {
      if (status == 200) {
        console.log("下载成功")
        hotPotato();
      } else {
        mui.toast(item.attachmentName + '下载失败')
        hotPotato();
      }
    });
    dtask.start();
  });
}
